// 引入重置样式
require("../../assets/css/reset.css");
// 引入公共样式
require("../../assets/css/basic.css");
// 引入矢量图
require("../../assets/fonts/iconfont.css");
// 引入当前样式
require("./register.less");

// 引入dom
const dom = require("../../utils/dom.js");
// 引入验证码模块
const CaptchaMini = require("captcha-mini");
// 引入axios模块
const axios = require("../../utils/axios.js");

window.addEventListener("DOMContentLoaded", () => {
    const error = dom.get("#error");  // 提示文字

    // 验证码
    /*不传值，统一走默认值*/
    let captcha = new CaptchaMini();
    let codeInit = "";
    captcha.draw(dom.get('#captcha'), r => {
        // console.log(r, '验证码1');
        codeInit = r.toLowerCase();
    });

    // 功能一：表单验证
    dom.get("#btn").addEventListener("click", () => {
        // 手机号验证
        const tel = dom.get("#tel").value;
        let regex = /^1[3456789]\d{9}$/;
        if(regex.test(tel)){
            error.textContent = "";
        }else{
            error.textContent = "手机号输入错误";
            return;
        }

        // 验证码验证
        const code = dom.get("#code").value.toLowerCase();
        if(code === codeInit){
            error.textContent = "";
        }else{
            error.textContent = "验证码输入错误";
            return;
        }

        // 密码验证
        const pwd = dom.get("#pwd").value;
        let ragex2 = /^[A-Za-z0-9]{6,}$/;
        if(ragex2.test(pwd)){
            error.textContent = "";
        }else{
            error.textContent = "请输入6位以上密码，不可写中文";
            return;
        }

        // 密码再次验证
        const pwd2 = dom.get("#pwd2").value;
        if(pwd2 === pwd){
            error.textContent = "";
        }else{
            error.textContent = "两次输入密码不一致";
            return;
        }

        // ajax验证
        axios.post("/api/user/register", {
            account:tel,
            password:pwd,
        }).then(response => {
            console.log(response);
            if(response.data.errno === 0){
                location.href = "login.html";
                alert("注册成功");
            }else{
                alert("注册失败" + response.data.message);
            }
        })
    })
})